﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Quebec.Silverlight.Animations
{
	public class SizeAnimation : AnimationBase
	{
		public static TimeSpan DefaultDuration = TimeSpan.FromMilliseconds(250);

		public SizeAnimation(double width, double height)
			: this(width, height, DefaultDuration)
		{
		}

		public SizeAnimation(double width, double height, TimeSpan duration)
		{
			Width = width;
			Height = height;
			Duration = duration;
		}

		public double Width
		{
			get;
			private set;
		}

		public double Height
		{
			get;
			private set;
		}

		public TimeSpan Duration
		{
			get;
			private set;
		}

		protected override Storyboard CreateStoryboard()
		{
			var storyboard = new Storyboard();

			var widthAnimation = new DoubleAnimationUsingKeyFrames();
			var heightAnimation = new DoubleAnimationUsingKeyFrames();

			Storyboard.SetTargetProperty(widthAnimation, new PropertyPath("(FrameworkElement.Width)"));
			Storyboard.SetTargetProperty(heightAnimation, new PropertyPath("(FrameworkElement.Height)"));

			storyboard.Children.Add(widthAnimation);
			storyboard.Children.Add(heightAnimation);

			widthAnimation.KeyFrames.Add(new SplineDoubleKeyFrame()
			{
				KeySpline = new KeySpline()
				{
					ControlPoint1 = new Point(0.528, 0),
					ControlPoint2 = new Point(0.142, 0.847)
				}
			});

			heightAnimation.KeyFrames.Add(new SplineDoubleKeyFrame()
			{
				KeySpline = new KeySpline()
				{
					ControlPoint1 = new Point(0.528, 0),
					ControlPoint2 = new Point(0.142, 0.847)
				}
			});

			return storyboard;
		}

		protected override void ApplyValues(Storyboard storyboard)
		{
			if (storyboard == null)
				throw new ArgumentNullException("storyboard");

			var widthAnimation = storyboard.Children[0] as DoubleAnimationUsingKeyFrames;
			var heightAnimation = storyboard.Children[1] as DoubleAnimationUsingKeyFrames;

			widthAnimation.KeyFrames[0].Value = Width;
			widthAnimation.KeyFrames[0].KeyTime = KeyTime.FromTimeSpan(Duration);
			heightAnimation.KeyFrames[0].Value = Height;
			heightAnimation.KeyFrames[0].KeyTime = KeyTime.FromTimeSpan(Duration);
		}
	}
}
